﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using Entity.Car_Rental;
using Entity.CommonEnums;
using System.Transactions;

namespace Data.Car_Rental
{
    public class OrderRespository : Car_RentalRepositoryBase, IOrderRespository
    {
        IOrderItemRespository iOrderItemRespository = null;
        IRentalRecordRepository iRentalRecordRepository = null;
        public OrderRespository()
        {
            iOrderItemRespository = new OrderItemRespository();
            iRentalRecordRepository = new RentalRecordRepository();
        }

        #region IOrderRespository 成员

        public Entity.VMessage GenerateOrder(Entity.Car_Rental.Order order)
        {
            VMessage vm = new VMessage();
            vm.IsComplete = false;
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    vm.Entity = this.InsertGetIDENTITY(order);
                    if (order.OrderItem_Extend != null && order.OrderItem_Extend.ToList().Count > 0)
                    {
                        order.OrderItem_Extend.ToList().ForEach(i => i.OrderID = (vm.Entity as Order).OrderID);
                        order.OrderItem_Extend.ToList().ForEach(j =>
                        {
                            OrderItem orderItem = iOrderItemRespository.InsertGetIDENTITY(j);
                            j.RentalRecord_Extend.OrderItemID = orderItem.OrderItemID;
                            iRentalRecordRepository.Insert(j.RentalRecord_Extend);
                        });
                    }
                    vm.IsComplete = true;
                    trans.Complete();
                }
                catch (Exception e)
                {
                    vm.AddItem(e.Message);
                    throw;//发布后不要throw，否则finally里面的语句将不被执行
                }
                finally
                {
                    trans.Dispose();//.net非托管资源，需要进行手动Dispose
                }

            }
            return vm;
        }

        public IQueryable<Entity.Car_Rental.Order> GetDetailModel()
        {
            var linq = from i in this.GetModel()
                       join j in iOrderItemRespository.GetDetailModel() on i.OrderID equals j.OrderID into list
                       select new Order_Ext
                       {
                           BuyerUserID = i.BuyerUserID,
                           CreateDate = i.CreateDate,
                           InvoiceAmount = i.InvoiceAmount,
                           InvoiceBody = i.InvoiceBody,
                           InvoiceTitle = i.InvoiceTitle,
                           Note = i.Note,
                           IsDelivery = i.IsDelivery,
                           IsInvoice = i.IsInvoice,
                           OrderAmount = i.OrderAmount,
                           OrderStatus = i.OrderStatus,
                           PayType = i.PayType,
                           ProductSaleAmount = i.ProductSaleAmount,
                           RankCommentStatus = i.RankCommentStatus,
                           ShippingAmount = i.ShippingAmount,
                           ShippingMethods = i.ShippingMethods,
                           Status = i.Status,
                           TaxAmount = i.TaxAmount,
                           UpdateDate = i.UpdateDate,
                           OrderItem_Extend = list,
                           OrderID = i.OrderID
                       };
            return linq;

        }

        public Entity.PagedList<Entity.Car_Rental.Order> GetOrder(Entity.VPredication vp, Entity.PagingParam pp)
        {
            var linq = this.GetDetailModel();
            return new PagedList<Order>(linq, pp.PageIndex, pp.PageSize);
        }

        public VMessage FinishOrder(Order order)
        {
            VMessage vm = new VMessage();
            vm.IsComplete = false;
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    //更新订单状态
                    this.Update(order);
                    //插入网站收支明细
                    //new WebAccountRecordsRepository().Insert(new WebAccountRecords
                    //{

                    //});
                    //更新网站总余额
                    //new WebAccountBalancesRepository().Update(new WebAccountBalances { });
                    //更新产品库存
                    new OrderItemRespository().GetDetailModel().Where(i => i.OrderID == order.OrderID).ToList().ForEach(i =>
                    {
                        new ProductRepository().UpdateProductCount(i.ProductID, -i.Quantity);
                        //car_rental明细记录
                        new RentalRecordRepository().Update(new RentalRecord { ID = i.RentalRecord_Extend.ID, Status = (int)RentalRecordStatus.Rented });

                    });
                    trans.Complete();

                }
                catch (Exception)
                {
                    // vm.AddItem(e.Message);
                    throw;
                }
                finally
                {

                    trans.Dispose();
                }
            }
            return vm;

        }
        #endregion

        #region IRepository<Order> 成员

        public void Update(Entity.Car_Rental.Order entity)
        {
            base.UpdateEntity(entity);
        }

        public void Update(IList<Entity.Car_Rental.Order> list)
        {
            base.UpdateEntity(list.Cast<EntityBase>().ToList());
        }

        public void Insert(Entity.Car_Rental.Order entity)
        {
            base.InsertEntity(entity);
        }

        public void Insert(IList<Entity.Car_Rental.Order> list)
        {
            base.InsertEntity(list.Cast<EntityBase>().ToList());
        }

        public Entity.Car_Rental.Order InsertGetIDENTITY(Entity.Car_Rental.Order entity)
        {
            base.InsertEntity(entity);
            return this.Find(entity.PrimaryKey);
        }

        public void Delete(Entity.Car_Rental.Order entity)
        {
            base.DeleteEntity(entity);
        }

        public void Delete(IList<Entity.Car_Rental.Order> list)
        {
            base.DeleteEntity(list.Cast<EntityBase>().ToList());
        }

        public IQueryable<Entity.Car_Rental.Order> GetModel()
        {
            return base.GetEntities<Order>().Where(i => i.Status != (int)Status.Deleted).Select(i => new Order_Ext
            {
                BuyerUserID = i.BuyerUserID,
                CreateDate = i.CreateDate,
                InvoiceAmount = i.InvoiceAmount,
                InvoiceBody = i.InvoiceBody,
                InvoiceTitle = i.InvoiceTitle,
                Note = i.Note,
                IsDelivery = i.IsDelivery,
                IsInvoice = i.IsInvoice,
                OrderAmount = i.OrderAmount,
                OrderStatus = i.OrderStatus,
                PayType = i.PayType,
                ProductSaleAmount = i.ProductSaleAmount,
                RankCommentStatus = i.RankCommentStatus,
                ShippingAmount = i.ShippingAmount,
                ShippingMethods = i.ShippingMethods,
                Status = i.Status,
                TaxAmount = i.TaxAmount,
                UpdateDate = i.UpdateDate,
                OrderID = i.OrderID
            });
        }

        public Entity.Car_Rental.Order Find(params object[] keyValues)
        {
            return base.Find<Order>(keyValues);
        }

        #endregion
    }
}
